
import io from 'socket.io-client/dist/socket.io.js'; 

interface WebSocketXOption {
  name: string;
}
export class WebSocketX { 

  url: string;

  name?: string;

  ws: any;

  constructor(url: string, option?: WebSocketXOption ) {
    this.url = url;
    this.name= option?.name;
    this.ws = io(url, {
      autoConnect: false
    });
  }

  open() {
    this.ws.open();
    this.registerEvent();
  }

  close() {
    this.ws.close();
    this.ws = undefined;
  }

  registerEvent() {
    this.ws.on('connect', () => {
      // this.ws.emit('server', 'hello world!');
      console.log(`${this.name}-连接成功`);
    });

    this.ws.on("disconnect", (reason: string) => {
      if (reason === "io server disconnect") {
        // the disconnection was initiated by the server, you need to reconnect manually
        this.ws.connect();
      }
    });
  }

  emit(key: string, value: any) {
    this.ws.emit(key, value);
  }

  on(key: string, callback: Function) {
    this.ws.on(key, callback);
  }

  removeAllListeners(key: string) {
    this.ws.removeAllListeners(key);
  }
}
